<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 千禧益达
 */
class QianxiyidaController extends PayController{
    protected $config;
    protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);
        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));
        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $return = $this->orderadd( $parameter );


        $data = array();
        $data['seller_id'] = $this->config['mch_id'];

        switch($this->config['paytype']){
            //微信
            case 1:
                $data['order_type'] = '2701';
                break;
            //支付宝
            case 3:
                $data['order_type'] = '2702';
                break;
            //qq
            case 8:
                $data['order_type'] = '2705';
                break;
            //微信H5
            case 2:
                $data['order_type'] = '2706';
                break;
            //支付宝H5
            case 4:
                $data['order_type'] = '2708';
                break;
            //QQ H5
            case 10:
                $data['order_type'] = '2707';
                break;
            //银联扫码
            case 11:
                $data['order_type'] = '2711';
                break;
            //银联快捷
            case 13:
                $data['order_type'] = '2703';
                break;
            //京东
            case 9:
                $data['order_type'] = '2709';
                break;
            //百度钱包
            case 7:
                $data['order_type'] = '2710';
                break;
            //网银跳转
            case 5:
            case 6:
                $data['order_type'] = '2704';
                break;
            default:
                $this->showmessage('不支持此产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }


        $data['pay_body'] = 'zf';
        $data['out_trade_no'] = $return['orderid'];
        $data['total_fee'] = $return['amount']*100;
        $data['notify_url'] = $return['notifyurl'];
        $data['return_url'] = $return['callbackurl'];
        $data['spbill_create_ip'] = getIP();
        $data['spbill_times'] = date("YmdHis", time());
        $data['noncestr'] = md5($data['spbill_times']);
        $data['remark'] = 'app';


        $merchant_private_key = file_get_contents("Files/Qianxiyida/merchant_private_key.txt");
        $merchant_private_key = openssl_get_privatekey($merchant_private_key);
        openssl_sign($this->getSignStr($data),$sign_info,$merchant_private_key,OPENSSL_ALGO_MD5);

        $data['sign'] = base64_encode($sign_info);
        $res = $this->http_poststr($this->config['gateway'], base64_encode(json_encode($data)));
        if(!$res){
            $this->showmessage('获取数据失败!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $res = json_decode($res, true);

        /*echo '<pre/>';
        echo "请求地址：". $this->config['gateway']."<br/>";
        print_r($data);
        print_r($res); exit;*/
        if(empty($res)){
            $this->showmessage('获取的数据格式不正确!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $code = $res['pay_url'];
        if(!$code){
            if($res['return_msg']){
                $this->showmessage($res['return_msg'],['code'=>C("THIRDCODES.".$this->class)]);
            }
            $this->showmessage('获取二维码失败!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        switch($product['paytype']){
            //微信H5
            case 2:
                //支付宝H5
            case 4:
                //QQ H5
            case 10:
                //银联快捷
            case 13:
                //京东wap
            case 14:
                //网银跳转
            case 5:
            case 6:
                header("location: {$code}"); exit;
        }

        header("location: {$code}");
    }

    //通知
    public function notifyurl(){
        //file_put_contents("a.txt",var_export($_POST,true)."\r\n\r\n");
        //file_put_contents("a.txt",var_export($_GET,true)."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", file_get_contents('php://input')."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", date("Y-m-d H:i:s",time())."\r\n\r\n", FILE_APPEND);

        $p = file_get_contents('php://input');
        /*$p = 'eyJvcGF5X3N0YXR1cyI6IjAiLCJvcmRlcl90eXBlIjoiMjcwOCIsIm91dF90cmFkZV9ubyI6IjIw
MTgwOTIyMTk0MzAwNTY5ODAyNiIsInBheV9zdGF0dXMiOiIxIiwicmV0dXJuX2NvZGUiOiJTVUND
RVNTIiwicmV0dXJuX21zZyI6Im9yZGVyX25vdGlmeSIsInNlbGxlcl9pZCI6IjU2MTcxMzI3NSIs
InNpZ24iOiJTaEF3Y08wTjZTTEtMOXRab0crSlVnMmJMUXRaMUlYbE0wUmhTU0lIVGo0azJaakdZ
cjVobTB3T2o5c05BNitNUDNld1FjeDByZnRYNmJCNGd4REsrZmdYa3ZvS0k2QnZYL0lGNXE0QlJB
eWZXR3NFam10SC96RCtVUm9sVG83alNrUTRCN244KzYreXh2SWRBN3Vua0JWaG9sV1Y3ZGYzbmE4
SmdoSkF3ZWNiZ2duUTQ2Q3BhL3ZFK3VxbDVpVnc1SHBpUCsvb0gvWTRTdWtDVWpaWGRoV2hsTXpa
VC9DQk9pODcxcGltK0F3VTFwRmJHK2hhaHFkZmhXNkNmT0dwbmR0cGdEK3VCY1NpQytOZGVhZEtm
bjJKZmxnaldOUmpVTVFSeHFSWXNWSjBQU0MvMW9zbU9lY3I0eGI0MDlBbjJYeEVMVldUSDdyK2lx
UkVEMXpCNHc9PSIsInN0YXRlIjoiMDAiLCJ0b3RhbF9mZWUiOjUwMDB9';*/

        if(!$p){
            exit("no_data");
        }


        $p = base64_decode($p);

        $resp = $p = json_decode($p, true);
        $web_public_key = file_get_contents("Files/Qianxiyida/web_public_key.txt");
        $web_public_key = openssl_get_publickey($web_public_key);
        $flag = openssl_verify($this->getSignStr($resp),base64_decode($resp['sign']),$web_public_key,OPENSSL_ALGO_MD5);

        if(!$flag){
            exit("sign_wrong");
        }

        /*
         * Array
            (
                [opay_status] => 0
                [order_type] => 2708
                [out_trade_no] => 201809221943005698026
                [pay_status] => 1
                [return_code] => SUCCESS
                [return_msg] => order_notify
                [seller_id] => 561713275
                [sign] => ShAwcO0N6SLKL9tZoG+JUg2bLQtZ1IXlM0RhSSIHTj4k2ZjGYr5hm0wOj9sNA6+MP3ewQcx0rftX6bB4gxDK+fgXkvoKI6BvX/IF5q4BRAyfWGsEjmtH/zD+URolTo7jSkQ4B7n8+6+yxvIdA7unkBVholWV7df3na8JghJAwecbggnQ46Cpa/vE+uql5iVw5HpiP+/oH/Y4SukCUjZXdhWhlMzZT/CBOi871pim+AwU1pFbG+hahqdfhW6CfOGpndtpgD+uBcSiC+NdeadKfn2JflgjWNRjUMQRxqRYsVJ0PSC/1osmOecr4xb409An2XxELVWTH7r+iqRED1zB4w==
                [state] => 00
                [total_fee] => 5000
            )
         */

        //获取订单信息
        $orderid = $p['out_trade_no'];
        $find = $this->checkOrderNotify($orderid);
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
     /*   M("Order")->where(array("pay_orderid"=>$orderid))->save(array(


        ));*/

        //获取渠道信息
        $this->config = Channel::getInstance()->find(['code'=>'Qianxiyida']);
        if(!$this->config){
            $this->config = M("Channel")->where(array('code'=>'Qianxiyida'))->find();
        }

        if(!$this->config){
            exit("get_tongdao_fail");
        }

        if($p['pay_status'] != 1){
            exit("pay_fail");
        }

        //处理支付
        //$this->EditMoney($find['pay_orderid'],"Qianxiyida",0);

        //回调成功
        //echo 'success'; exit;
        $this->async($find['pay_orderid'],'success');
    }

    public function callBackUrl(){
        echo '处理成功'; exit;
    }

    function getSignStr($Obj){
        foreach ($Obj as $k => $v) {
            if($v != '' && $k != 'sign'){
                $Parameters[$k] = $v;
            }
        }
        ksort($Parameters);
        return urldecode($this->formatBizQueryParaMap($Parameters));
    }

    function formatBizQueryParaMap($paraMap){
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if($v != null && $v != ''){
                $buff .= $k . "=" . $v . "&";
            }
        }
        $reqPar = '';
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff)-1);
        }
        return urlencode($reqPar);
    }

    function http_poststr($url, $data_string) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($data_string))
        );
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();

        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return $return_content;
    }
}